package com.zetor.ms.application.service.base.impl;

import com.zetor.ms.application.adapter.ISeataAdapter;
import com.zetor.ms.application.service.base.ITransactionService;
import com.zetor.ms.core.sequence.SnowflakeIdWorker;
import com.zetor.ms.repository.entity.seata.DemoOrderEntity;
import com.zetor.ms.repository.entity.spd.PhaDsDrugBookEntity;
import com.zetor.ms.repository.mapper.mybatisplus.DemoOrderMapper;
import com.zetor.ms.repository.mapper.spd.SpdMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;

/**
 * 事务回滚 demo service
 *
 * @author zlc
 * @date 2021/11/05
 */

@Service
public class TransactionServiceImpl implements ITransactionService {
    @Autowired
    private ISeataAdapter seataAdapter;
    @Autowired
    private DemoOrderMapper demoOrderMapper;
    @Autowired
    private SpdMapper spdMapper;
    @Resource
    private SnowflakeIdWorker snowflakeIdWorker;

    /**
     * 分布式事务处理操作
     * 包含：本地事务回滚、远程事务补偿操作
     *
     * @return
     */
    @Override
    public Long seataCase1() {
        // 本地保存操作
        Long id = seataSave();
//        int i = 1/0;
        return id;
    }

    private Long seataSave() {
        // 本地保存操作
        DemoOrderEntity order = new DemoOrderEntity();
        Long id = snowflakeIdWorker.nextId();
        order.setId(id);
        order.setStatus(1);
        order.setOrderName("seata_order");
        order.setAddress("沈阳市");
        demoOrderMapper.insert(order);
        return id;
    }

    private Long seataStock(Long orderId) {
        return seataAdapter.seataCCase4(orderId);
    }

    /**
     * 分布式事务处理操作
     * 包含：本地事务回滚、远程事务补偿操作
     *
     * @return
     */
    @Override
    public Long seataCase4() {
        Long orderId = seataSave();

        Long stockId = seataStock(orderId);
        int i = 1/0;
        return stockId;
    }

    /**
     * 分布式事务处理操作
     * 包含：本地事务回滚、远程事务补偿操作
     *
     * @return
     */
    @Override
    public Long seataCase9() {
        // 本地保存操作
        PhaDsDrugBookEntity spd = new PhaDsDrugBookEntity();
        String id = snowflakeIdWorker.getStrId();
        spd.setPhaDsDrugBookId(id);
        spd.setHospitalId("h001");
        spd.setCompoundId("c001");
        spd.setBookSn("z001");
        spd.setDrugDept("dd");
        spd.setDrugCode("dcode");
        spd.setUnitPrice(new BigDecimal(1));
        spd.setBookQty(new BigDecimal(1));
        spd.setOperCode("oc");
        spd.setOperDatetime(new Timestamp(System.currentTimeMillis()));
        spdMapper.insert(spd);
//        int i = 1/0;
        return Long.parseLong(id);
    }
}
